package com.online_vote_system.demo.controller;

import com.online_vote_system.demo.service.CompetitionService;
import com.online_vote_system.demo.service.VoteService;
import com.online_vote_system.demo.vo.Audience;
import com.online_vote_system.demo.vo.Competition;
import com.online_vote_system.demo.vo.Player;
import com.online_vote_system.demo.vo.Vote;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@Controller
public class VoteController {

    @Autowired
    VoteService voteService;
    @Autowired
    CompetitionService competitionService;
    @GetMapping("/doVote/{comId}")
    public String doVote(@PathVariable(value = "comId") String comId,
                         @RequestParam(value = "fg") String fg,
                         Model model,
                         HttpServletRequest request){
        log.info("投票编号=>"+comId+"投票人员=>"+fg);
        HttpSession session = request.getSession();
        Audience audience = (Audience) session.getAttribute("loginUser");
        Vote vote = voteService.findOne(String.valueOf(audience.getAudId()),comId);
        if (vote == null){
            synchronized (this){
                voteService.doVote(comId,fg);
                voteService.insertVote(comId,String.valueOf(audience.getAudId()));
            }
            model.addAttribute("msg","0");
        }else {
            model.addAttribute("msg","1");
        }
        Competition competition = competitionService.getOneByType();
        model.addAttribute("competition",competition);
        return "html/Audience/showScore";
    }

}
